﻿namespace Digitalmes.Application.Mes;

/// <summary>
/// 设备警报信息查询服务
/// </summary>
public sealed class EquipAlarmItemQueryService : IEquipAlarmItemQueryService
{
    const string CacheName = "__EquipAlarmSettingCache";

    private readonly IServiceProvider _serviceProvider;
    private readonly IMemoryCache _memoryCache;

    public EquipAlarmItemQueryService(IServiceProvider serviceProvider,
        IMemoryCache memoryCache)
    {
        _serviceProvider = serviceProvider;
        _memoryCache = memoryCache;
    }

    /// <summary>
    /// 获取全部的警报项。
    /// </summary>
    /// <returns></returns>
    public async Task<List<EquipAlarmItem>> GetAllAsync()
    {
        return await _memoryCache.GetOrCreateAsync(CacheName, async cacheEntry =>
        {
            var repo = _serviceProvider.GetRequiredService<SugarRepository<EquipAlarmItem>>();
            return await repo.GetListAsync();
        }) ?? new(0);
    }

    /// <summary>
    /// 通过编号集合获取警报设置项集合
    /// </summary>
    /// <param name="noList">编号集合</param>
    /// <returns></returns>
    public async Task<List<EquipAlarmItem>> GetByNoAsync(IEnumerable<int> noList)
    {
        var alarms = await GetAllAsync();
        return alarms.Where(s => noList.Contains(s.Pos)).ToList();
    }

    /// <summary>
    /// 通过编号集合获取警报设置项集合
    /// </summary>
    /// <param name="equipName">设备名称</param>
    /// <param name="noList">编号集合</param>
    /// <returns></returns>
    public async Task<List<EquipAlarmItem>> GetByNoAsync(string? equipName, IEnumerable<int> noList)
    {
        var alarms = await GetAllAsync();
        return alarms.Where(s => s.EquipName == equipName && noList.Contains(s.Pos)).ToList();
    }

    /// <summary>
    /// 清除警报项目。
    /// </summary>
    public void Clear()
    {
        _memoryCache.Remove(CacheName);
    }
}
